package com.financing.model.user;
import com.financing.components.payment.Gateway;
import com.financing.model.Data;
import com.financing.model.base.BaseUser;
import com.financing.model.invest.Trade;
import com.financing.model.invest.Withdraw;
import com.financing.util.DateUtil;
import com.financing.util.Money;
import com.financing.util.Str;
import com.financing.util.XmlHelper;

@SuppressWarnings("serial")
public class User extends BaseUser<User> {
	public static final User me = new User().dao();

	/**
	 * 刷新用户可用余额
	 */
	public void refereshAmount() {
		this.put("available_amount","0.00");
		this.put("freezeble_amount","0.00");
		double fm = 0.00;
		
		if(this.getIsBindBankCard()==1) {
			try{
				XmlHelper res = Gateway.post("/BalanceAction.action", 
					Data.put(
						"mchnt_txn_ssn",DateUtil.getTimeStamp(),
						"mchnt_txn_dt",DateUtil.format(DateUtil.GATEWAY_DEFAULT_FORMAT),
						"cust_no",getCode(),
						"sign","cust_no,mchnt_cd,mchnt_txn_dt,mchnt_txn_ssn"
					)
				);
				// 查询用户余额	
				if(res.isSuccess()){
					if(Str.nb(res.getStr("/results/result/ca_balance"))) {
						this.put("available_amount", String.valueOf(Money.format(Double.valueOf(res.getStr("/results/result/ca_balance"))/100)));
					}
					if(Str.nb(res.getStr("/results/result/cf_balance"))) {
						fm += Money.format(Double.valueOf(res.getStr("/results/result/cf_balance"))/100);
					}
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			
			// 已投资未满标，归入冻结金额
			Trade t = Trade.me.findFirst("select sum(amount) as amount from trade where (status='trading' or status='full') and user_id=?", this.getId());
			double tm = Money.get(t.getDouble("amount"));	
			
			// 提现未到账金额，归入冻结金额
			Withdraw w = Withdraw.me.findFirst("SELECT sum(amount) as amount FROM withdraw WHERE status='apply' AND user_id=?", this.getId());
			double wm = Money.get(w.getDouble("amount"));	
			
			this.put("freezeble_amount", String.valueOf(fm+tm+wm));	
		}
	}
	
	/**
	 * 获取用户可用余额
	 */
	public double getAvailableAmount() {
		double amt = 0.0;
		if(this.getIsBindBankCard()==1) {
			try{
				XmlHelper res = Gateway.post("/BalanceAction.action", 
					Data.put(
						"mchnt_txn_ssn",DateUtil.getTimeStamp(),
						"mchnt_txn_dt",DateUtil.format(DateUtil.GATEWAY_DEFAULT_FORMAT),
						"cust_no",getCode(),
						"sign","cust_no,mchnt_cd,mchnt_txn_dt,mchnt_txn_ssn"
					)
				);
				// 查询用户余额	
				if(res.isSuccess()){
					if(Str.nb(res.getStr("/results/result/ca_balance"))) {
						amt = Money.format(Double.valueOf(res.getStr("/results/result/ca_balance"))/100);
					}
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return amt;
	}
	
	/**
	 * 刷新用户可用余额
	 */
	public Staff getStaff() { 
		return Staff.me.findFirst("select * from staff where user_id=?", getId());
	}
}